package com.gowiny.ddns.core.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;

public class AppUtils {
    private static String formatMac(byte[] mac) {
        StringBuilder sb = new StringBuilder();
        for (byte b : mac) {
            sb.append(String.format("%02X", b)).append(":");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    public static String[] getIpsByMac(String mac) {
    	List<String> list = new ArrayList<String>();
    	try{
    		mac = mac.replaceAll("[^\\w]", ":").toUpperCase();
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface;
            Enumeration<InetAddress> inetAddresses;
            InetAddress inetAddress;
            while (networkInterfaces.hasMoreElements()) {
                networkInterface = networkInterfaces.nextElement();

                if (networkInterface.isLoopback() ||
                        !networkInterface.isUp() ||
                        networkInterface.isVirtual()
                ) {
                    continue;
                }
                String itemMac = formatMac(networkInterface.getHardwareAddress());
                if(!itemMac.equals(mac)){
                    continue;
                }
                inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    inetAddress = inetAddresses.nextElement();
                    if(null != inetAddress){
                    	String ip = inetAddress.getHostAddress();
                    	ip = ip.replaceAll("%.*$", "");
                    	list.add(ip);
                    }
                }
                break;
            }
        }catch (Exception e){
        }
    	return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
    }
    public static String getIpByMac(String mac,int targetIndex) {
    	String ip = null;
    	String[] ips = getIpsByMac(mac);
    	if(ips.length > targetIndex) {
    		ip = ips[targetIndex];
    	}
    	return ip;
    }
    
    public static String getIpv4ByMac(String mac,int targetIndex) {
    	String ip = getIpByMac(mac, targetIndex);
    	if(null != ip && 
    			ip.indexOf(".") == -1) {
    		ip = null;
    	}
    	return ip;
    }
    public static String getIpv6ByMac(String mac,int targetIndex) {
    	String ip = getIpByMac(mac, targetIndex);
    	if(null != ip && 
    			ip.indexOf(":") == -1) {
    		ip = null;
    	}
    	return ip;
    }
    
}
